//
//  NetworkTools.swift
//  newshaohuo
//
//  Created by shaohuo on 2018/1/26.
//  Copyright © 2018年 shaohuo. All rights reserved.
//

import UIKit
import Alamofire
import SwiftProgressHUD

let URL_ROOT_DOMAIN : String = "\(URL_ROOT)/api/index/index"

let publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAocVOllR76mfBbvU3qyQQrBeSUDruTDhecBFXJX3AFZTwSOEjWBxsUH/3hNrCKLmBXjN5emIETaPWJNwRUTA9L0q2pEfVV+8imUfOAAHVNF8KcWbxFy9mgmuBHbHuuHbJcO4tulBaX3QkY2NtSKkyoi37G/o0+Suy3LJ6bBf9ulsZSlPf0DLI4+PFAbG15VP2NNHDgc4+v5GdkHMXbTNpsmR6xawJR4Xduu4kIKEmSHX1TkistGMJdI7CPDOaH9npvyfCUtG7jI5Vlhml61/stEZctSNzV37cr/iga7J12XVRVVVYGhd5dw6aZ8Gibv3VM0hoh8+vXhGY4ZpryxFq7QIDAQAB"

let privateKey = "MIIEogIBAAKCAQEAocVOllR76mfBbvU3qyQQrBeSUDruTDhecBFXJX3AFZTwSOEjWBxsUH/3hNrCKLmBXjN5emIETaPWJNwRUTA9L0q2pEfVV+8imUfOAAHVNF8KcWbxFy9mgmuBHbHuuHbJcO4tulBaX3QkY2NtSKkyoi37G/o0+Suy3LJ6bBf9ulsZSlPf0DLI4+PFAbG15VP2NNHDgc4+v5GdkHMXbTNpsmR6xawJR4Xduu4kIKEmSHX1TkistGMJdI7CPDOaH9npvyfCUtG7jI5Vlhml61/stEZctSNzV37cr/iga7J12XVRVVVYGhd5dw6aZ8Gibv3VM0hoh8+vXhGY4ZpryxFq7QIDAQABAoIBAD8onIUe2P5sod3jSWe8/fFihpJiX7VMcLqKWp7dmMgUTTf3BmiZOES5oXayPgnOW07fA/efGxUA+VOMxAoRrmGvZt1+2jGpwLVdjnT8QjRfQuGBknE95WTX+iIQ3SYR4pX/t8S9KHuKCcbwA7PRs14UW6zRpCsAP6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工具类单例
    static let sharedInstance = NetworkTools()
    
}

//RSA加密
extension NetworkTools {
    
    func encrypt(parameters: AnyObject) -> String? {
        
        let data = try! JSONSerialization.data(withJSONObject: parameters, options: [])
        
        let sourceStr = String(data: data, encoding: String.Encoding.utf8)
        
        //公钥加密
        let encryptStr = RSAEncryptor.encryptString(sourceStr, publicKey: publicKey)
        
        //私钥解密
        let decrypeStr = RSAEncryptor.decryptString(encryptStr, privateKey: privateKey)
        
        print("加密前:\(String(describing: sourceStr)) 加密后:\(String(describing: encryptStr))  解密后:\(String(describing: decrypeStr))")
        
        return encryptStr
    }
}

// MARK: - 基础请求方法
extension NetworkTools {
    //    in view: UIView = UIApplication.shared.keyWindow!,title: String? = nil
    /**
     GET请求
     
     - parameter URLString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
//    func getRequest(urlString: String, parameters: AnyObject, headers:HTTPHeaders, successed:@escaping (_ responseObject: JSON) -> (), failed: @escaping (_ error: Error?) -> ())   {
//
//        let encryptStr = encrypt(parameters: parameters)
//
//        Alamofire.request(rootDomain+urlString, method: .get, parameters: ["param":String(encryptStr!)], encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
//
//            switch response.result {
//            case .success(let value):
//                let json = JSON(value)
//                successed(json)
//                print(json)
//
//            case .failure(let error):
//                failed(error)
//                print("error:\(error)")
//            }
//
//        }
//
//    }
    
    /**
     POST请求
     
     - parameter URLString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func postRequest(urlString: String, parameters: AnyObject, headers:HTTPHeaders, successed:@escaping (_ resultDict: NSDictionary) -> ())   {
        
//        parameters.set("shr", forKey: "app_name")
        
        let encryptStr = encrypt(parameters: parameters)
        
//        SwiftProgressHUD.showWait()
        Alamofire.request(URL_ROOT_DOMAIN+urlString, method: .post, parameters: ["param":String(encryptStr!)], encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
//            SwiftProgressHUD.hideAllHUD()
            switch response.result {
            case .success(let responseObject):
                let resultDict = responseObject as! NSDictionary
                if  resultDict["code"] as? String  == "000000" {
                    successed(resultDict)
                }else if resultDict["code"] as? Int  == 801005 {
                    SwiftProgressHUD.showOnlyText("账号异地登录，请重新登录")
                    UserTicketModel.sharedInstance.logout()
                    JPUSHService.setTags([], completion: { (iResCode, iTags, seq) in
                        print("极光=\(iResCode),\(iTags!)")
                    }, seq: 0)
                    let loginVc = LoginController()
                    UIApplication.shared.keyWindow?.rootViewController?.present(loginVc, animated: true, completion: nil)
                }else {
                    SwiftProgressHUD.showOnlyText((resultDict["msg"]) as! String)
                }
            case .failure(let error):
                print("请求失败:\(error)")
            }
        }
    }
    
    /**
     字典转换为JSONString
     
     - parameter dictionary: 字典参数
     
     - returns: JSONString
     */
    func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
}

